package Thread;

class MyBlockingQueue{
    private int head = 0;
    private int tail = 0;
    private int usedSize = 0;
    private int[] array = new int[1000];

    public synchronized void put(int value) throws InterruptedException {
        while (usedSize == array.length) {
            wait();
        }
        array[tail] = value;
        tail++;
        if (tail >= array.length) {
            tail = 0;
        }
        usedSize++;
        notify();
    }

    public synchronized Integer take() throws InterruptedException {
        while (usedSize == 0) {
            wait();
        }
        Integer result = array[head];
        head++;
        if (head >= array.length) {
            head = 0;
        }
        usedSize--;
        notify();
        return result;
    }
}

public class ThreadDemo16 {

    public static void main(String[] args) throws InterruptedException {
//        MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread customer = new Thread(()->{
            while (true) {
                int res = 0;
                try {
                    res = queue.take();
                    System.out.println("消费的元素:" + res);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread producer =new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    System.out.println("生产的元素:"+count);
                    queue.put(count++);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        customer.start();
    }

}
